package com.james.aspect;

import com.james.anno.Log;
import com.james.domain.User;
import com.james.service.LogService;
import com.james.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;

/**
 * @ClassName: LogAspect
 * @Author: JamesWang
 * @Date: 2021/4/22 15:08
 * @Description:
 * @Version:1.0
 */
@Aspect
@Component
public class LogAspect {

    @Autowired
    private UserService userService;

    @Autowired
    private LogService logService;

    @Around("@annotation(com.james.anno.Log)")
    public Object LogAround(ProceedingJoinPoint joinPoint) {
        Object result = null;
        // 1.拿到方法签名
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        // 方法名称
        String methodName = method.getName();
        Log log = method.getAnnotation(Log.class);
        // 注解的属性值
        String operation = log.operation();
        // 方法参数
        Object[] args = joinPoint.getArgs();
        // ip
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert requestAttributes != null;
        HttpServletRequest request = requestAttributes.getRequest();
        String ip = request.getRemoteHost();
        // 拿到当前用户
        String userId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        User user = userService.getById(userId);
        // 目标方法的执行时间
        long start = System.currentTimeMillis();
        try {
           result = joinPoint.proceed(args);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        long end = System.currentTimeMillis();
        long time = end - start;

        // 构建日志对象 存入数据库中
        com.james.domain.Log operationLog = com.james.domain.Log.builder()
                .userName(user.getUserName())
                .operation(operation)
                .method(methodName)
                .params(Arrays.toString(args))
                .time(time)
                .ip(ip)
                .createTime(new Date()).build();

        logService.save(operationLog);
        return result;
    }
}
